package pw.goyd.game.manager;


import pw.goyd.db.RedisUtil;
import pw.goyd.game.constant.setting.Command;
import pw.goyd.game.logic.AnnounceResponse;
import pw.goyd.game.model.Room;
import pw.goyd.game.model.Seat;
import pw.goyd.game.server.Log;
import pw.goyd.game.server.Server;
import pw.goyd.protocol.model.Response;
import pw.goyd.subscribe.PlayerCustomer;

public class GameManager implements Command {
    /**
     * 发送广播
     *
     * @param msg 消息
     */
    public static void sendAnnounceMsg(String msg) {
        AnnounceResponse announceResponse = new AnnounceResponse();
        announceResponse.setMsg(msg);
        Response response = new Response();
        response.setCmd(CMD_SCROLL);
        response.setData(announceResponse.getBytes());
        response.setTime(0);

        RedisUtil.publishData("broadcast.*".getBytes(), response.getAllBytes());
    }

    /**
     * 发送广播
     *
     * @param msg    消息
     * @param roomID 房间iD
     */
    public static void sendAnnounceMsg(String msg, int roomID) {
        AnnounceResponse announceResponse = new AnnounceResponse();
        announceResponse.setMsg(msg);
        Response response = new Response();
        response.setCmd(CMD_SCROLL);
        response.setData(announceResponse.getBytes());
        response.setTime(0);

        RedisUtil.publishData(("room." + roomID).getBytes(), response.getAllBytes());
    }

    /**
     * 发送广播
     *
     * @param msg 消息
     * @param room 房间obj
     */
    public static void sendAnnounceMsg(String msg, Room room) {
        AnnounceResponse announceResponse = new AnnounceResponse();
        announceResponse.setMsg(msg);
        Response response = new Response();
        response.setCmd(CMD_SCROLL);
        response.setData(announceResponse.getBytes());
        response.setTime(0);

        RedisUtil.publishData(("room." + room.getRoomID()).getBytes(), response.getAllBytes());
    }

    /**
     * 检测房间是否能自动开始
     */
    public static void checkStart(PlayerCustomer pc) {
        //传入null
        if (pc == null)
            return;

        //拿到所在房间
        int roomID = pc.getRoomID();
        Room room = RoomManager.getRoom(roomID);

        // 是否正在游戏
        if (room == null || room.isGame())
            return;

        int count = 0;          // 初始化准备的人数
        //	遍历取得准备人数
        for (Seat s : room.getSeats()) {
            if (s.player != null && s.player.isReady()) {
                count++;
            }
        }

        Log.getLogger().info("room [" + roomID + "] 玩家准备人数---->" + count);

        // 两人开始倒计时
        if (count >= 2) {
            if (room.getReadyTime() == -1) {
                // 开始计时
                Log.getLogger().info("room [" + roomID + "] 游戏开始");
                room.setReadyTime(Server.getServerTime());
                RoomManager.reayRoom.add(room);     // 加入等待处理房间 交给服务器计时器处理
                room.pubTimeDown();
            }
        }

    }

}
